import { PureComponent } from "react";
import { Flex, Tag, InputItem } from "antd-mobile";
import MToast from "../../Util/MToast"
import { isNull, combineDefaultArr, handleInputFocusBlur, getMDrawerFullHeight } from "../../../utils/helper"
import MIcon from "../../MIcon"
import MDrawer from "../../MDrawer/MDrawer"
interface Props {
	value: any,
	other_label?: any,
	setFieldsValue: Function,
	getFieldValue: Function,
	list: any[],
	value_datatype?: string,
	field_mapping?: object,
	field: string[],
	onChange: Function,
	place_holder?: string,
	formData: object,
	label?: string,
	required?: any,
	show_label?: any,
	tips?: string,
	label_width?: any,
	hasError: boolean,
	errorMsg: string,
	label_text_color?: string,
	label_text_align?: any,
	other_place_holder?: string
}
interface State {
	value: any,
	open: boolean,
	selectMoreValue: any,
	otherCode: any,
	otherName: any
}
export default class MySelectMoreOther extends PureComponent<Props, State>{
	public state: State = {
		value: this.props.value,
		open: false,
		selectMoreValue: "",
		otherCode: "",
		otherName: ""
	}
	onOpenChange = () => {
		this.setState({ open: !this.state.open });
	};
	handleCancel = () => {
		this.onOpenChange()
	};
	handleOk = () => {
		let { selectMoreValue, otherCode, otherName } = this.state;
		let { other_label, setFieldsValue, getFieldValue, list, value_datatype = "string", field_mapping, field } = this.props;
		if (!isNull(selectMoreValue)) {
			let newSelectMoreValue = "," + selectMoreValue + ",";
			if (newSelectMoreValue.indexOf("," + otherCode + ",") != -1) {// 有其他
				if (isNull(otherName)) {
					MToast.fail("请选择：" + other_label, 1.5, null, false)
				}
				else {
					newSelectMoreValue = newSelectMoreValue.replace("-1,", "");
					newSelectMoreValue = newSelectMoreValue.substring(1);
					newSelectMoreValue = newSelectMoreValue.substring(0, newSelectMoreValue.length - 1);
					newSelectMoreValue += ",-1";
					this.changeValue(newSelectMoreValue);
					//在这里赋field[1]的值
					let newVal = combineDefaultArr(list, selectMoreValue, "code", value_datatype);
					let selectOption = [];
					newVal.map(item => {
						let arr = list.filter(i => i.code === item)[0];
						selectOption.push(arr);
					});
					let nameKey = "name";
					if (!isNull(field_mapping) && !isNull(field_mapping[field[1]])) {
						nameKey = field_mapping[field[1]];
					}
					let str = ",";
					selectOption.map(item => {
						str += item[nameKey] + ","
					});
					str += otherName + ",";
					str = str.substring(1);
					str = str.substring(0, str.length - 1);
					getFieldValue([field[1]]);
					setFieldsValue({
						[field[1]]: str
					});
					this.onOpenChange()
				}
			}
			else {
				this.setState({
					otherName: undefined
				});
				setTimeout(() => {
					this.changeValue(selectMoreValue);
					this.onOpenChange()
				})
			}
		}
		else {
			this.changeValue(undefined);
			this.onOpenChange()
		}
	};
	selectItemClick = (item) => {
		let { selectMoreValue } = this.state;
		let { code } = item;
		let newValue = "";
		if (isNull(selectMoreValue)) {
			newValue = code + "";
		}
		else {
			let n = "," + selectMoreValue + ",";
			if (n.indexOf("," + code + ",") != -1) {
				newValue = n.replace("," + code + ",", ",");
			}
			else {
				newValue = n + code + ","
			}
			newValue = newValue.substring(1);
			newValue = newValue.substring(0, newValue.length - 1);
		}
		if (isNull(newValue)) {
			newValue = undefined
		}
		this.setState({
			selectMoreValue: newValue
		})
	};

	componentWillMount() {
		this.setState({
			otherCode: -1
		})
	}
	componentWillReceiveProps(nextProps) {
		// Should be a controlled component.
		if ('value' in nextProps) {
			let value = nextProps.value;
			this.setState({
				value
			});
		}
	}
	changeValue = (value) => {
		if (!('value' in this.props)) {
			this.setState({
				value: value
			});
		}
		this.triggerChange(value);
	};

	triggerChange = (changedValue) => {
		const onChange = this.props.onChange;
		if (onChange) {
			onChange(changedValue);
		}
	};
	onChange = (value) => {
		this.changeValue(value);
	};
	renderName = (valueList) => {
		let { place_holder, formData, field } = this.props;
		let names = formData[field[1]];
		if (isNull(names)) {
			if (!isNull(valueList) && valueList.length > 1) {
				return <Flex className="select-more" wrap="wrap" justify="end">
					{
						valueList.length > 0 ? valueList.map((i, k) => {
							return <Tag disabled key={k}>{i.name}</Tag>
						}) : <div style={{ color: "rgb(187,187,187)" }}>{place_holder}</div>
					}
				</Flex>
			}
			else {
				return <div style={{ color: "rgb(187,187,187)", textAlign: "right" }}>{place_holder}</div>
			}
		}
		else {
			names = names.split(",");
			return <Flex className="select-more" wrap="wrap" justify="end">
				{
					names.length > 0 ? names.map((i, k) => {
						return <Tag disabled key={k} >{i}</Tag>
					}) : <div style={{ color: "rgb(187,187,187)" }}>{place_holder}</div>
				}
			</Flex>
		}
	};
	render() {
		let { field, label, required, show_label, tips, label_width = 5, list, formData, hasError, errorMsg, value_datatype = "string", label_text_color, label_text_align = "left", other_label = "其他", other_place_holder } = this.props;
		let isNumber = value_datatype == "number";
		let isShowLabel = isNull(show_label) || show_label == 1;
		let isRequired = required == 1;
		let { value, open, selectMoreValue, otherCode, otherName } = this.state;

		let valueList = [];
		if (!isNull(value) && list.length > 0) {
			let newVal = "," + value + ",";
			list.map(item => {
				let { code } = item;
				if (isNumber) {
					code = Number(code);
				}
				if (newVal.indexOf("," + code + ",") != -1) {
					valueList.push(item);
				}
			});
			if (value.toString().indexOf(-1) != -1) {
				valueList.push({
					code: otherCode,
					name: otherName
				})
			}
		}
		if (list && list.length > 0) {
			list = list.map(i => {
				return {
					...i,
					label: i.name,
					value: i.code
				}
			})
		}
		list.push({
			code: otherCode,
			name: other_label
		});

		let requiredClass = "am-list-item am-input-item am-list-item-middle mi-text mi-radio-group";
		if (isRequired) {
			requiredClass += " required"
		}
		if (!isNull(label_text_align)) {
			requiredClass += " label-text-align-" + label_text_align
		}
		if (hasError) {
			requiredClass += " am-input-error"
		}
		let onExtraClick = () => {
			MToast.info(tips, 2, null, false)
		};
		let labelClass = "am-input-label am-input-label-";
		if (isNull(label_width)) {
			labelClass += "3"
		}
		else {
			labelClass += label_width
		}
		return (
			<div>
				<div className={requiredClass} style={{ fontSize: "16px" }} data-flex>
					{
						isShowLabel ? <div className={labelClass} style={{ color: label_text_color }}>
							{label}
						</div> : <div></div>
					}
					<div style={{ color: "#888" }} className="am-list-line" data-flex="dir:left box:last" onClick={() => {
						if (isNull(list) || list.length == 0) {
							MToast.info("暂无数据", 2, null, false)
						}
						else {
							let newVal = value;
							this.setState({
								selectMoreValue: newVal
							});
							//如果包含其他
							if (!isNull(newVal) && newVal.toString().indexOf("-1") != -1) {
								let newName = formData[field[1]];
								if (!isNull(newName)) {
									let valueArr = newVal.split(",");
									let nameArr = newName.split(",");
									let otherName1 = nameArr[valueArr.indexOf("-1")];
									this.setState({
										otherName: otherName1
									})
								}
							}
							this.onOpenChange();
						}
					}}>
						{this.renderName(valueList)}
						<div data-flex="cross:center box:last">
							<p style={{ width: "16px" }}><MIcon type="xiayiye" style={{ color: "rgb(187, 187, 187)" }} /></p>
							<div className="am-input-error-extra mi" onClick={(e) => {
								e.stopPropagation();
								MToast.info(errorMsg, 2, null, false)
							}}
							/>
						</div>
					</div>
				</div>
				{tips && <p className="tipsStyle">{tips}</p>}
				<MDrawer open={open} position="bottom" height={getMDrawerFullHeight} onOpenChange={() => {
					this.setState({
						open: !this.state.open
					})
				}}>
					<div className="am-picker-popup-header" >
						<div className="am-picker-popup-item am-picker-popup-header-left" onClick={this.handleCancel}>取消</div>
						<div className="am-picker-popup-item am-picker-popup-title">{label}</div>
						<div className="am-picker-popup-item am-picker-popup-header-right" onClick={this.handleOk}>确定</div>
					</div>
					<div style={{ overflow: "auto", WebkitOverflowScrolling: "touch" }}>
						{
							list.map(item => {
								let { code, name, desc, url } = item;
								if (isNumber) {
									code = Number(code);
								}

								let img = "./image/check_box_multi_no.png";
								let isYes = false;
								if (!isNull(selectMoreValue)) {
									let newSelectMoreValue = "," + selectMoreValue + ",";
									if (newSelectMoreValue.indexOf("," + code + ",") != -1) {
										isYes = true;
									}
								}
								if (isYes) {
									img = "./image/check_box_multi_yes.png";
								}
								return (
									<div style={{ fontSize: "16px", padding: "10px 10px", borderBottom: "1px solid #f7f7f7" }} data-flex="dir:left cross:center main:start" key={code} onClick={() => {
										this.selectItemClick(item)
									}}>
										<img style={{ width: '20px', height: "20px", marginRight: "10px" }} src={img} alt="" />
										<div data-flex="dir:left cross:center">
											{
												!isNull(url) ? <img style={{ width: "50px", height: "50px", marginRight: "10px" }} src={url} alt="" /> : null
											}
											<div>
												<p>{name}</p>
												<p style={{ color: "#999", fontSize: "14px", marginTop: "2px" }}>{desc}</p>
											</div>
										</div>
									</div>
								)
							})
						}
						{
							<InputItem
								placeholder={other_place_holder}
								value={this.state.otherName}
								disabled={("," + selectMoreValue + ",").indexOf("," + otherCode + ",") == -1}
								style={{ borderBottom: "1px solid #f7f7f7", height: "40px" }}
								onFocus={() => {
									handleInputFocusBlur()
								}}
								onBlur={() => {
									handleInputFocusBlur(true);
								}}
								onChange={(e) => {
									this.setState({
										otherName: e
									})
								}}
							/>
						}
					</div>
					<div></div>
				</MDrawer>
			</div>
		)
	}
}
